<template>
  <el-form-item
    v-if="!item.disabled"
    id="box"
    :label="item.name"
    :label-width="item.labelWidth"
    class="picker-box rel input-form-item"
    prop="content">
    <div slot="label" :title="item.name" class="ellipsisTwo input-form-label">{{ item.name }}</div>
    <el-input id="multiMonthPicker" v-model="value[item.keyword]" :placeholder="placeholder" class="input-style" type="text" size="small" readonly @focus="showBox = true" @clear="handleClear">
      <i slot="prefix" class="el-input__icon el-icon-date" />
      <i v-if="showClear" slot="suffix" class="el-input__icon el-icon-circle-close clear-style" @click="handleCancel" />
    </el-input>
    <!-- 年份月份选择弹框 -->
    <div v-show="showBox" id="selectBox" class="select-content-box">
      <div class="content-area">
        <!-- 年份 -->
        <div class="flex year-box">
          <div class="cursor" @click="reduceYear">
            <i class="el-icon-d-arrow-left" />
          </div>
          <div class="year-text">{{ currentYear }}年</div>
          <div class="cursor" @click="addYear">
            <i class="el-icon-d-arrow-right" />
          </div>
        </div>
        <!-- 月份 -->
        <div class="months-box">
          <el-checkbox-group v-model="optTime[curIndex].queryTime" class="flex" @change="onChange">
            <el-checkbox
              v-for="(it, idx) in DateList[curIndex].queryTime"
              :label="`${DateList[curIndex].TimeYear}-${
                it <= 9 ? `0${it}` : it
              }`"
              :key="idx"
              class="month-item"
            >
              {{ monthMap[it] }}月
            </el-checkbox>
          </el-checkbox-group>
        </div>
      </div>
      <div class="btn-box">
        <el-button size="mini" type="primary" plain @click="handleSubmit">确定</el-button>
        <el-button size="mini" plain @click="handleCancel">取消</el-button>
      </div>
    </div>
  </el-form-item>
</template>
<script>
export default {
  props: {
    placeholder: {
      type: String,
      default: '请选择导出月份'
    },
    item: {
      type: Object,
      default: () => {
        return {};
      }
    },
    value: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  data() {
    return {
      DateList: [], // 年份月份数组
      optTime: [], //
      currentYear: '', // 当前年份
      curIndex: 0, // 当前年份下标值
      optTimes: [], // 点击月份时的所有选中结果
      resultTimes: [], // 点击“确定”按钮后的选择结果
      showBox: false, // 是否显示月份选择弹框
      inputValue: '',
      showClear: false,
      monthMap: {
        '1': '一',
        '2': '二',
        '3': '三',
        '4': '四',
        '5': '五',
        '6': '六',
        '7': '七',
        '8': '八',
        '9': '九',
        '10': '十',
        '11': '十一',
        '12': '十二'
      }
    };
  },
  created() {
    this.init();
  },
  mounted() {
    document.addEventListener('click', e => {
      // 获取弹窗对象
      const boxArea = document.getElementById('box');
      // 判断弹窗对象中是否包含点击对象
      if (boxArea && !boxArea.contains(e.target)) {
        // 判断当前选中月份与上次点击“确定”按钮时的选择结果是否一致
        const equalArr = this.resultTimes.sort().toString() === this.optTimes.sort().toString();
        if (!equalArr) {
          // 将选择结果恢复到上次点击“确定”按钮时的结果
          this.optTimes = this.resultTimes;
          // 将输入框的值恢复到上次点击“确定”按钮时的值
          this.inputValue = this.optTimes.join(',');
          // 根据输入框是否有值来判断清空图标是否渲染
          this.showClear = this.inputValue !== '';
          // 将月份选中结果恢复到上次点击“确定”按钮时的选中月份
          const _opt = this.resultTimes.map(v => v.substring(0, 4));
          for (const item in this.optTime) {
            this.optTime[item].queryTime = [];
            _opt.map((items, indexs) => {
              if (items === this.optTime[item].TimeYear) {
                this.optTime[item].queryTime.push(this.resultTimes[indexs]);
              }
            });
          }
        }
        // 关闭弹框
        this.showBox = false;
      }
    });
    // 设置月份弹窗位置
    const multiMonthPicker = document.getElementById('multiMonthPicker');
    const offsetObj = this.getOffset(multiMonthPicker);
    const selectBox = document.getElementById('selectBox');
    selectBox.style.left = offsetObj.left;
    selectBox.style.top = offsetObj.top + 5;
  },
  methods: {
    getOffset(el) {
      const scrollTop =
        el.getBoundingClientRect().top +
        document.body.scrollTop +
        document.documentElement.scrollTop;
      const scrollLeft =
        el.getBoundingClientRect().left +
        document.body.scrollLeft +
        document.documentElement.scrollLeft;
      return {
        top: scrollTop,
        left: scrollLeft
      };
    },
    // 初始化数据，获取前20年，然后循环 每一年里面都有12个月的 得到数组 opTime 和 DateList
    init() {
      const _opt = [];
      const _optTime = [];
      const arr = new Array(12);
      const optDate = this.getDateList();
      optDate.map((item, index) => {
        // 月份选择时el-checkbox-group绑定的值
        _optTime[index] = {
          TimeYear: item,
          queryTime: []
        };
        // 给每一年份设置12个月份，el-checkbox初始化显示时使用
        _opt[index] = {
          TimeYear: item,
          queryTime: []
        };
        for (let i = 1; i <= arr.length; i++) {
          _opt[index].queryTime.push(i);
        }
      });
      this.optTime = _optTime;
      this.DateList = _opt;
    },
    // 获取近20年年份列表，倒序排列，最新一年在最前面
    getDateList() {
      const Dates = new Date();
      const year = Dates.getFullYear();
      this.currentYear = year;
      const optDate = [];
      for (let i = year - 20; i <= year; i++) {
        optDate.push(i);
      }
      return optDate.reverse();
    },
    handleSubmit() {
      this.inputValue = this.optTimes.join(',');
      this.value[this.item.keyword] = this.optTimes.join(',');
      this.showClear = this.inputValue !== '';
      // 将点击“确定”按钮的选择结果保存起来
      this.resultTimes = this.optTimes;
      this.showBox = false;
      this.$emit('submitMonths', { val: this.inputValue, key: this.item.keyword });
      this.$emit('changeValue', this.value);
    },
    handleClear() {
      this.$emit('resetMonths');
    },
    handleCancel() {
      const Dates = new Date();
      const year = Dates.getFullYear();
      this.currentYear = year;
      this.optTimes = [];
      for (const i in this.optTime) {
        this.optTime[i].queryTime = [];
      }
      this.inputValue = '';
      this.value[this.item.keyword] = '';
      this.showClear = false;
      this.resultTimes = [];
      this.showBox = false;
      this.$emit('resetMonths');
    },
    reduceYear() {
      // 如果已经是最后一年了，则年份不能再减少了
      if (this.curIndex === this.DateList.length - 1) return;
      // 当前下标值+1，根据下标值获取年份值
      this.curIndex = this.curIndex + 1;
      this.currentYear = this.DateList[this.curIndex].TimeYear;
    },
    addYear() {
      // 当前年份不继续增加
      if (this.curIndex === 0) return;
      // 当前下标值-1，根据下标值获取年份值
      this.curIndex = this.curIndex - 1;
      this.currentYear = this.DateList[this.curIndex].TimeYear;
    },
    // 选择月份
    onChange() {
      // 遍历optTime中已选择的月份，将已选结果塞到optTimes数组中
      const _opt = this.optTime;
      const arr = [];
      for (const item in _opt) {
        if (_opt[item].queryTime.length > 0) {
          _opt[item].queryTime.filter((v) => {
            arr.push(v);
          });
        }
      }
      this.optTimes = arr;
      this.inputValue = this.optTimes.join(',');
      this.value[this.item.keyword] = this.optTimes.join(',');
      this.showClear = this.inputValue !== '';
      this.$emit('submitMonths', { val: this.inputValue, key: this.item.keyword });
      this.$emit('changeValue', this.value);
    }
  }
};
</script>
<style lang="scss" scoped>
.picker-box {
  &::v-deep {
    .clear-style {
      display: none;
    }
    .input-style:hover .clear-style {
      display: block;
    }
    .select-content-box {
      position: fixed;
      z-index: 2022;
      background: #ffffff;
      border: 1px solid #e5e5e5;
      border-radius: 3px;
      .content-area {
        .flex {
          flex-wrap: wrap;
        }
        .year-box {
          padding: 15px 0;
          justify-content: space-between;
          border-bottom: 1px solid #e5e5e5;
          .cursor {
            width: 15%;
            cursor: pointer;
            text-align: center;
            &:hover {
              color: #409eff;
            }
          }
          .year-text {
            text-align: center;
          }
        }
      }
    }
    .months-box {
      .month-item {
        width: 25% !important;
        margin: 20px 0 !important;
        text-align: center;
        &:hover {
          color: #409eff;
        }
      }
      .el-checkbox__input {
        display: none !important;
      }
      .el-checkbox__label {
        padding-left: 0px !important;
      }
    }
    .btn-box {
      border-top: 1px solid #e5e5e5;
      padding: 10px 10px 10px 0;
      display: flex;
      align-items: center;
      justify-content: flex-end;
    }
    .el-form-item__label {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      height: 32px;
    }
  }
}
.input-form-label {
  line-height: 1.2 !important;
}
</style>
